package de.sendorian.app.forumArchive;


import java.io.File;
import java.io.FilenameFilter;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.hamcrest.Matcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import de.sendorian.app.forumArchive.domain.Forum;
import de.sendorian.app.forumArchive.domain.Topic;

@Component
public class Collector {
	
	private @Value("#{props.download_dir}") String downloadDir;

	private FilenameFilter filter = new FilenameFilter() {
		public boolean accept(File dir, String name) {
			return StringUtils.endsWithIgnoreCase(name, ".png");
		}
	};

	public Set<String> collectImagesInForumDirs(List<Forum> forums, Matcher<Topic> topicMatcher) {
		Set<String> allDirs = new LinkedHashSet<String>();
		for (Forum forum : forums) {
			for (Topic topic : forum.getTopics()) {
				if (topicMatcher.matches(topic)) {
					String topicDir = downloadDir + forum.getName() + File.separator
					    + topic.getName();
					allDirs.add(topicDir);
				}
			}
		}
		return collectImagesInFolders(allDirs);
	}


	public Set<String> collectImagesInFolders(Set<String> dirs) {
		Set<String> allFiles = new LinkedHashSet<String>();
		for (String sDir : dirs) {
			File dir = new File(sDir);
			if (dir.exists()) {
				for (String file : dir.list(filter)) {
					allFiles.add(dir.getAbsolutePath() + File.separator + file);
				}
			}
		}
		return allFiles;
	}

}
